var express = require('express');
var router = express.Router();

var md5 = require('md5');
var request = require('request');
var consts = require('../common/constants');

var router = express.Router();

//活动列表
router.get('/list', function(req, res, next) {
    var params = {};
    var uid = req.query.uid;
    var token = JSON.stringify(params) + "|" + consts.MD5_String;
    token = md5(token);
    var url = consts.APP_HOST + 'coupon/list.htm?token=' + token;
    var options = {
        url: url,
        method: 'POST',
        json: true,
        body: params
    };

    request(options, function(err, httpResponse, body) {
        if (1 == body.MobileHead.Code) {
    		console.log(body.MobileBody.list);
             res.render('activity', {
               // listJ: JSON.stringify(body.MobileBody),
                list: body.MobileBody,
                uid: uid
             })

        } else {
            res.send('404');
        }
    });
});

//获取单一优惠劵信息
router.get('/getone', function(req, res, next) {
    var params = {
        couponId: req.query.cid
    };

    var token = JSON.stringify(params) + "|" + consts.MD5_String;
    token = md5(token);
    var url = consts.APP_HOST + 'coupon/getone.htm?token=' + token;
    var options = {
        url: url,
        method: 'POST',
        json: true,
        body: params
    };

    request(options, function(err, httpResponse, body) {
        if (1 == body.MobileHead.Code) {
            console.log(body.MobileBody.list);
             res.render('activity', {
                coupon: body.MobileBody
             })

        } else {
            res.send('404');
        }
    });
});

//领取优惠劵
router.get('/use', function(req, res, next) {
    var params = {
        userId: req.query.uid,
        couponId: req.query.cid,
        orderSource: 'weixin'
    };

    var token = JSON.stringify(params) + "|" + consts.MD5_String;
    token = md5(token);
    var url = consts.APP_HOST + 'coupon/use.htm?token=' + token;
    var options = {
        url: url,
        method: 'POST',
        json: true,
        body: params
    };

    request(options, function(err, httpResponse, body) {
        if (1 == body.MobileHead.Code) {
            console.log(body.MobileBody);
            res.send(body.MobileHead);
        } else {
            res.send(body.MobileHead);
        }
    });
});


module.exports = router;